package com.briup.jdbc.execute;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class InsertExecute<T> extends AbstractExecute {

	List<Map<String, Object>> requiresMapsList;

	public InsertExecute() {
		super();
	}

	public InsertExecute(String sql, Class param, List<Map<String, Object>> requiresMapsList) {
		super(sql, param);
		this.requiresMapsList = requiresMapsList;
	}

	// 主要方法
	public int insert(Connection conn) throws Exception {
		int result = 0;
		try {

			PreparedStatement ps = conn.prepareStatement(sql);
			if (requiresMapsList.size() == 0) {
				throw new Exception("sql-insert-data is null!");
			}
//			System.err.println("size>>" + requiresMapsList.size());
			if (requiresMapsList.size() == 1) {
				Map<String, Object> map = requiresMapsList.get(0);
				Object[] array = map.values().toArray();
				for (int i = 0; i < array.length; i++) {
					ps.setObject(i + 1, array[i]);
				}
				result = ps.executeUpdate();
			} else {
				int temp = 1;
				for (Map<String, Object> map : requiresMapsList) {
					Object[] array = map.values().toArray();
					for (int i = 0; i < array.length; i++) {
						ps.setObject(i + 1, array[i]);

					}
					ps.addBatch();
					if (temp++ % 1000 == 0) {
						result += ps.executeBatch().length;
					}
				}
				result += ps.executeBatch().length;
			}
		} catch (Exception e) {
			throw e;
		}
		return result;
	}

}
